package com.example.shop.rabbitmq.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Configuration
public class RabbitmqConfig {

    @Qualifier("mqObjectMapper")
    @Resource
    ObjectMapper objectMapper;

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate();
        template.setConnectionFactory(connectionFactory);
        //发布时的消息转换器
        template.setMessageConverter(new Jackson2JsonMessageConverter(objectMapper));
        return template;
    }

    /**
     * 手动构建容器，处理消息
     * @param connectionFactory rabbitmq服务器连接工厂
     * @return
     */
    @Bean("rabbitListenerContainerFactory")//令RabbitAnnotationDrivenConfiguration配置类里的SimpleRabbitListenerContainerFactory失效
    public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(SimpleRabbitListenerContainerFactoryConfigurer configurer, ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        configurer.configure(factory, connectionFactory);
        //默认排队执行，即单线程concurrentConsumers=1
        factory.setConcurrentConsumers(10);
        factory.setMaxConcurrentConsumers(30);
        factory.setConnectionFactory(connectionFactory);
        //设置消息转换器，即消费者消费该消息时进行的消息转换器
        //也可以自定义消息转换器，实现MessageConverter接口即可
        factory.setMessageConverter(new Jackson2JsonMessageConverter());
        return factory;
    }

}
